package com.qf.set.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.qf.common.annotation.Log;
import com.qf.common.constant.UserConstants;
import com.qf.common.core.controller.BaseController;
import com.qf.common.core.domain.AjaxResult;
import java.util.Objects;
import com.qf.common.core.domain.TreeSelect;
import com.qf.common.enums.BusinessType;
import com.qf.common.utils.SecurityUtils;
import com.qf.set.domain.TmsDepartment;
import com.qf.set.service.ITmsDepartmentService;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/tms-dept")
public class TmsDepartmentController extends BaseController
{
    // private String prefix = "system/dept";

    @Autowired
    private ITmsDepartmentService deptService;

    // @PreAuthorize("@ss.hasPermi('system:dept:view')")
    // @GetMapping()
    // public String dept()
    // {
    //     return prefix + "/dept";
    // }

    /**
     * 查询部门列表
     */
    // @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/tms/list")
    @ResponseBody
    public List<TmsDepartment> list(TmsDepartment dept)
    {
        List<TmsDepartment> list = deptService.selectDeptList(dept);
        return list;
    }

    /**
     * 新增部门
     */
    // @GetMapping("/add/{parentId}")
    // public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    // {
    //     mmap.put("dept", deptService.selectDeptById(parentId));
    //     return prefix + "/add";
    // }

    /**
     * 新增保存部门
     */
    @PostMapping("")
    @ResponseBody
    // @PreAuthorize("@ss.hasPermi('system:tms-dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    public AjaxResult addSave(@Validated @RequestBody TmsDepartment dept)
    {
        System.out.println(dept.toString());
        if (dept.getParentId() == null) {
            dept.setParentId(0L);
        }
        if (Objects.equals(UserConstants.NOT_UNIQUE, deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreator(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    // @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    // @GetMapping("/edit/{id}")
    // public String edit(@PathVariable("id") Long id, ModelMap mmap)
    // {
    //     TmsDepartment dept = deptService.selectDeptById(id);
    //     mmap.put("dept", dept);
    //     if (SecurityUtils.isAdmin(id))
    //     {
    //         mmap.put("parentDept", null);
    //     }
    //     else
    //     {
    //         mmap.put("parentDept", deptService.selectDeptById(dept.getParentId()));
    //     }
    //     return prefix + "/edit";
    // }

    /**
     * 修改保存部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping("")
    @ResponseBody
    public AjaxResult editSave(@Validated @RequestBody TmsDepartment dept)
    {
        System.out.println(dept.toString());
        if (dept.getId() == null) {
            return AjaxResult.error("部门ID不能为空");
        }
        TmsDepartment existingDept = deptService.selectDeptById(dept.getId());
        if (existingDept == null) {
            return AjaxResult.error("部门不存在");
        }
        if (dept.getParentId() == null) {
            dept.setParentId(0L);
        }
        if (Objects.equals(UserConstants.NOT_UNIQUE, deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.warn("存在子部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 选择部门树
     */
    // @GetMapping("/selectDeptTree/{deptId}")
    // public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap)
    // {
    //     mmap.put("dept", deptService.selectDeptById(deptId));
    //     return prefix + "/tree";
    // }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody

    public List<TreeSelect> treeData()
    {
        List<TreeSelect> treeSelects = deptService.selectDeptTreeSelect();
        return treeSelects;
    }

    /**
     * 查询所有部门（用于选择上级部门）
     */
    @GetMapping("/all")
    @ResponseBody

    public AjaxResult getAllDept()
    {
        List<TreeSelect> deptTreeSelect = deptService.selectDeptTreeSelect();
        return AjaxResult.success(deptTreeSelect);
    }

    /**
     * 查询部门详情
     */
    @GetMapping("/{deptId}")
    @ResponseBody

    public AjaxResult getDept(@PathVariable("deptId") Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public boolean checkDeptNameUnique(TmsDepartment dept)
    {
        return deptService.checkDeptNameUnique(dept);
    }
    /**
     * 获取部门树形结构数据
     */
    @GetMapping("/treeSelect")
    @ResponseBody
    public AjaxResult treeSelect()
    {
        List<TreeSelect> treeSelects = deptService.selectDeptTreeSelect();
        System.out.println(treeSelects);
        return AjaxResult.success(treeSelects);
    }

}